package com.njtoyo.taxi.admin.cmb;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.library.payment.cmb.CmbPayClient;
import com.njtoyo.taxi.admin.library.payment.cmb.config.CmbPayConfig;
import com.njtoyo.taxi.admin.library.payment.cmb.pojo.CmbBillDownload;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverServiceLog;
import com.njtoyo.taxi.admin.mapper.master.entity.Taxi;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mapper.secondary.entity.OrderBankBill;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.OrderBankBillMapper;
import com.njtoyo.taxi.admin.service.data.DriverServiceLogService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@SpringBootTest
@ActiveProfiles(value = "prod")
public class BillCreate {

    @Autowired
    private RideOrderMapper rideOrderMapper;
    @Autowired
    private SimpleCallRideOrderMapper simpleCallRideOrderMapper;
    @Autowired
    private OrderBankBillMapper orderBankBillMapper;


    @Test
    public void driver() {
        Date data = DateUtil.offsetDay(DateUtil.date(), -4);
        String billDate = DateUtil.formatDate(data);
        log.info("开始执行对账任务,对账日期：{}", billDate);
        CmbBillDownload download = new CmbBillDownload();
        download.setBillDate(billDate);
        download.setMerchantNo(CmbPayConfig.mch_id);
        download.setBillType("JH_JP");
        //设置文件存储目录
        String activeProfile = SpringUtil.getActiveProfile();
        String filePatth = null;
        if ("prod".equals(activeProfile)) {
            filePatth = "/Users/saber/Desktop/upload/bill/" + DateUtil.format(data, DatePattern.SIMPLE_MONTH_PATTERN);
        } else {
            filePatth = "/Users/saber/Desktop/upload/bill/" + DateUtil.format(data, DatePattern.SIMPLE_MONTH_PATTERN);
        }
        if (!FileUtil.exist(filePatth)) {
            FileUtil.mkParentDirs(filePatth);
        }
        String fileUrl = filePatth + "/" + billDate + ".xlsx";

        try {
            List<OrderBankBill> cacheBankBills = new ArrayList<>();
            String downloadUrl = CmbPayClient.billDownloadUrl(download);
            if (StrUtil.isNotBlank(downloadUrl)) {
                File file = HttpUtil.downloadFileFromUrl(downloadUrl, new File(fileUrl));
                log.info("对账单存储地址：{},下载结果：{}", fileUrl, file.exists());
                if (file.exists()) {//存在表示下载成功
                    //读取文件内容
                    ExcelReader reader = ExcelUtil.getReader(fileUrl);
                    List<List<Object>> readAll = reader.read();
                    CollUtil.forEach(readAll, (obj, index) -> {
                        List<Object> listObje = obj;
                        if (index >= 12) {
                            OrderBankBill orderBankBill = new OrderBankBill();
                            orderBankBill.setMerchantOrderNo(Convert.toStr(listObje.get(2)));
                            orderBankBill.setBankOrderNo(Convert.toStr(listObje.get(3)));
                            orderBankBill.setThirdPartyOrderNo(Convert.toStr(listObje.get(4)));
                            orderBankBill.setDealDate(Convert.toStr(listObje.get(6)));
                            orderBankBill.setDealTime(Convert.toStr(listObje.get(7)));
                            orderBankBill.setDealCompleteDate(Convert.toDate(listObje.get(8)));
                            orderBankBill.setDealAmount(Convert.toBigDecimal(listObje.get(9)));
                            orderBankBill.setBrokerage(Convert.toBigDecimal(listObje.get(11)));
                            cacheBankBills.add(orderBankBill);
                        }
                    });
                    Map<String, OrderBankBill> bankBillMap = cacheBankBills.stream().collect(Collectors.toMap(OrderBankBill::getMerchantOrderNo, Function.identity()));
                    Date startDate = DateUtil.beginOfDay(DateUtil.parseDate(billDate));
                    Date endDate = DateUtil.endOfDay(DateUtil.parseDate(billDate));

                    List<Map<String, Object>> rideOrderList = rideOrderMapper.getRideAndSimpleOrder(startDate, endDate);
                    System.out.println(rideOrderList);
                    for (Map map : rideOrderList) {
                        String merchantNo = MapUtil.getStr(map, "number");
                        BigDecimal amount = MapUtil.get(map, "farePaid", BigDecimal.class);
                        String outTradeNumber = MapUtil.getStr(map, "outTradeNumber");
                        Date payTime = MapUtil.getDate(map, "payTime");
                        OrderBankBill bankBill = bankBillMap.get(merchantNo);
                        if (ObjectUtil.isNotNull(bankBill)) {
                            bankBill.setOrderAmount(amount);
                            bankBill.setResult(bankBill.getDealAmount().compareTo(amount) == 0 ? "ok" : "error");
                        } else {
                            bankBill = new OrderBankBill();
                            bankBill.setMerchantOrderNo(merchantNo);
                            bankBill.setThirdPartyOrderNo(outTradeNumber);
                            bankBill.setOrderAmount(amount);
                            bankBill.setDealCompleteDate(payTime);
                            bankBill.setResult("error");
                        }
                        orderBankBillMapper.insert(bankBill);
                    }
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }
}
